<?php
/**
 *客户管理
*/

namespace app\admin\controller\Record;
use PhpOffice\PhpWord\TemplateProcessor;
use app\admin\controller\Admin;
use think\facade\App;
use think\facade\Db;
use xhadmin\service\admin\record\CustomerService;
use xhadmin\db\Customer as CustomerDb;
use think\facade\Cache;

class Customer extends Admin {


	/*会员管理*/
	function index(){
        //p(session('admin'));exit;

        if (!$this->request->isAjax()){
			return $this->display('record/customer/index');
		}else{
			$limit  = $this->request->post('limit', 0, 'intval');
			$offset = $this->request->post('offset', 0, 'intval');
			$page   = floor($offset / $limit) +1 ;

			$id_card= $this->request->param('id_card', '', 'strip_tags,trim');
			$first_name = $this->request->param('first_name', '', 'strip_tags,trim');
			$birth_year = $this->request->param('birth_year', '', 'strip_tags,trim');
            $id= $this->request->param('id', '', 'strip_tags,trim');
			//$last_name = $this->request->param('last_name', '', 'strip_tags,trim');
            if(!empty($id_card)){
                $where['id_card'] = ['like','%'.$id_card.'%'];
            }
            if(!empty($birth_year)){
                $where['birth_day'] = ['like','%'.$birth_year.'%'];
            }
            if(!empty($first_name)){
                $where['first_name|last_name|passport_info'] = ['like','%'.$first_name.'%'];
            }
            /*if(!empty($last_name)){
                $where['last_name'] = ['like','%'.$last_name.'%'];
            }*/
            if(!empty($id)){
                $where['id'] = ['=',$id];
            }
            $where['status'] = ['=',0];
			$limit = ($page-1) * $limit.','.$limit;
            //p($where);exit;
			try{
				$res = CustomerService::pageList(formatWhere($where),$limit,'*',$orderby = 'id desc');
				foreach ($res['list'] as $key=>&$val) {
				    $val['work_year_month'] = $val['work_year'].'年'.$val['work_month'].'个月'.$val['work_times'].'次';
                    $val['name'] = $val['first_name'].'</br> '.$val['last_name'];
                }
				$list = $res['list'];
			}catch(\Exception $e){
				exit($e->getMessage());
			}

			$data['rows']  = $list;
			$data['total'] = $res['count'];
			return json($data);
		}
	}

	/*添加*/
	function add(){
		if (!$this->request->isPost()){
			return $this->display('record/customer/info');
		}else{
            //$data = $this->request->post();
            //p($data);exit;
			$postField = 'status,id_card,idcardimg,idcardimgel,bankimg,wjbhzimg,first_name,last_name,birth_day,
			religion,addr,expiry_date,id_card_upside_no,id_card_upside_two,work_year,work_month,mobile,director,is_rename,is_hz_dg,
			is_yhb_dg,is_introducer,introducer,introducer_id,director_id,translater_id,is_jlzdg,qkd_info,work_times';
			$data = $this->request->only(explode(',',$postField),'post');
			//p($data);exit;
            /*if(empty($data['id_card']) || empty($data['idcardimg']) || empty($data['idcardimgel'])
                || empty($data['bankimg']) || empty($data['wjbhzimg'])) {
                return json(['status'=>'01','msg'=>'信息确少']);
            }*/
            if(empty($data['id_card'])) {
                return json(['status'=>'01','msg'=>'信息确少']);
            }
            $is_idcard = CustomerDb::countList(['id_card'=>$data['id_card']]);
            if($is_idcard) {
                return json(['status'=>'01','msg'=>'该客户已经存在']);
            }
			try {
                $now = time();
				$insert_id = CustomerService::add($data);
				$dataLog['c_id'] = $insert_id;
				$dataLog['id_card'] = $data['id_card'];
				$dataLog['status'] = 0;
				$dataLog['create_by'] = session('admin.userid');
				$dataLog['create_time'] = $now;
                Db::name("customer_log")->insert($dataLog);
//                $introducer = [
//                    'bank_img' =>$data['jsrbankimg'],
//                    'mobile' =>$data['introducer_mobile'],
//                    'id_card' =>$data['id_card'],
//                    'name' =>$data['introducer'],
//                    'create_time'=>$now
//                ];
//                Db::name("introducer")->insert($introducer);
			} catch (\Exception $e) {
				$this->error($e->getMessage());
			}
			return json(['status'=>'00','msg'=>'添加成功']);
		}
	}

	/*修改*/
	function update(){
		if (!$this->request->isPost()){
			$id = $this->request->get('id','','intval');
			if(!$id) $this->error('参数错误');
            $info = CustomerDb::getInfo($id);
            //p($info);exit;
            if(empty($info['idcard_info'])) {
                $idcard_info = [
                    'id_card' => $info['id_card'],
                    'expiry_day' => !empty($info['expiry_date']) ? date('Y-m-d', strtotime($info['expiry_date'])) : '',
                    'addr'=>$info['addr'],
                    'number' => '',
                    'number_1' => '',
                    'number_2' => '',
                    'number_3' => !empty($info['id_card_upside_two']) ? $info['id_card_upside_two'] : '',
                    'religion' => !empty($info['religion']) ? $info['religion'] : '佛教',
                    'birth_day' => !empty($info['birth_day']) ? date('Y-m-d', strtotime($info['birth_day'])) : '',
                    'first_name' => !empty($info['first_name']) ? $info['first_name'] : '',
                    'last_name' => !empty($info['last_name']) ? $info['last_name'] : '',
                    'sign_name' => '',
                    'number_day' => '',
                    'numer_user' => '吴明',
                    'dispatch_day' => '',//签证日期
                    'numer_sign_day' => date('Y-m-d'),
                    'id_card_posive_no' => '',
                    'id_card_upside_no' => !empty($info['id_card_upside_no']) ? $info['id_card_upside_no'] : '',
                ];
                $info['idcard_info'] = json_encode($idcard_info);
            }


            if(empty($info['passport_info'])) {
                $passport_info = [
                    'user_2_day' =>  date('Y-m-d'),
                    'user_2_name' => '',
                    'user_2_date1' => date('Y-m-d'),
                    'lastData_time' => date('Y-m-d'),
                    'proveData_time' =>'',
                    'user_2_signNum1' =>'',
                    'user_2_signNum2' =>'',
                    'user_2_person1' =>'CHATURONT CHAIYAKAM',
                    'user_2_person2' =>'MISS PRANEE PHOMSUPAR',
                    'user_2_person3' =>'Mr.Chaturont Chaiyakam',
                    'personApplytion' => '吴   惠',
                ];
                $passport_info['arr'][0] = [
                    'user_2_en' => $info['first_name'].$info['last_name'],
                    'user_2_th' => $info['first_name'].$info['last_name'],
                    'user_2_sex' => '-',
                    'user_2_kind' => '-',
                    'user_2_statu' => '-',
                    'user_2_number' => '-',
                    'user_2_codeNum' => $info['id_card'],
                    'user_2_endDate' => date('Y-m-d'),
                    'user_2_birthDay' => date('Y-m-d'),
                    'user_approveDay' => date('Y-m-d'),
                    'user_2_microfilm' => '-'
                ];
                $info['passport_info'] = json_encode($passport_info);
            }
			$this->view->assign('info',checkData($info));
			return $this->display('record/customer/info');
		}else{
            $postField = 'id,status,id_card,idcardimg,idcardimgel,bankimg,wjbhzimg,first_name,last_name,birth_day,
			religion,addr,expiry_date,id_card_upside_no,id_card_upside_two,work_year,work_month,mobile,director,is_rename,is_hz_dg,
			is_yhb_dg,is_introducer,introducer,introducer_id,director_id,translater_id,is_jlzdg,qkd_info,work_times';
			$data = $this->request->only(explode(',',$postField),'post');
			try {
                CustomerService::update($data);
//                if($data['is_introducer'] ==1) {
//                    $introducer = [
//                        'bank_img' =>$data['jsrbankimg'],
//                        'mobile' =>$data['introducer_mobile'],
//                        'id_card' =>$data['id_card'],
//                        'name' =>$data['introducer']
//                    ];
//                    Db::name('introducer')->where(['id_card'=>$data['id_card']])->update($introducer);
//                }

			} catch (\Exception $e) {
				$this->error($e->getMessage());
			}
			return json(['status'=>'00','msg'=>'修改成功']);
		}
	}

	/*改为泰外交部送件状态*/
    function status() {
        if (!$this->request->isPost()){
            $ids = $this->request->param('ids');
            /*$id = $this->request->get('id','','intval');
            if(!$id) $this->error('参数错误');
            $info = CustomerDb::getInfo($id);
            $this->view->assign('info',checkData($info));
            $id_card_fee = Db::name("customer")->field('id_card_fee')->where([['status','>',0],['id_card_fee','>',0]])->order('id','desc')->find();
            if($info['is_rename']!=1) {
                $pass_port_fee = 0;
            } else {
                $pass_port_fee_arr = Db::name("customer")->field('pass_port_fee')->where([['status','>',0],['pass_port_fee','>',0]])->order('id','desc')->find();
                if(!empty($pass_port_fee_arr)) {
                    $pass_port_fee = $pass_port_fee_arr['pass_port_fee'];
                } else {
                    $pass_port_fee = 100;
                }
            }
            $this->view->assign('id_card_fee',empty($id_card_fee)?150:$id_card_fee['id_card_fee']);
            $this->view->assign('pass_port_fee',$pass_port_fee);*/
            $this->view->assign('ids',$ids);
            $this->view->assign('id_card_fee',150);
            $this->view->assign('pass_port_fee',100);
            return $this->display('record/customer/status');
        }else{

            $postField = 'id,status,id_card_fee,pass_port_fee';
            $data = $this->request->only(explode(',',$postField),'post');
            $where['id'] = $ids = explode(',',$data['id']);

            try {
                $now = time();
                Db::startTrans();
                unset($data['id']);
                CustomerService::editWhere($where,$data);
                $turnover = $profit_loss_log =[];
                foreach ($ids as $id) {
                    $data['id'] = $id;
                    $info = CustomerDb::getInfo($data['id']);
                    //损益表
                    $pass_port_fee =  [
                        'subject' => 10,
                        //'sub_subject' => '',
                        'income_amount' =>0,
                        'outcome_amount' =>$data['id_card_fee'],
                        'related_index' =>$data['id'],
                        'created_time' => $now,
                        'created_d' => date('Ymd',$now),
                        'created_y' => date('Y',$now),
                        'created_ym' => date('Ym',$now)
                    ];
                    array_push($profit_loss_log,$pass_port_fee);

                    $pass_port_fee = [
                        'subject' => 20,
                        //'sub_subject' => '',
                        'income_amount' =>0,
                        'outcome_amount' =>$data['pass_port_fee'],
                        'related_index' =>$data['id'],
                        'created_time' => $now,
                        'created_d' => date('Ymd',$now),
                        'created_y' => date('Y',$now),
                        'created_ym' => date('Ym',$now)
                    ];
                    array_push($profit_loss_log,$pass_port_fee);


                    $turnover_id_card_fee = [
                        'type' =>1,
                        'sub_type' =>1,
                        'subject' =>10,
                        'director_id' =>$info['director_id'],
                        'introducer_id' =>$info['is_introducer'] ==1?$info['introducer_id']:0,
                        'customer_id' => $data['id'],
                        'customer_idcard' =>$info['id_card'],
                        'amount' => $data['id_card_fee'],
                        'related_index' => $data['id'],
                        'created_time' => $now,
                        'created_d' => date('Ymd',$now),
                        'created_y' => date('Y',$now),
                        'created_ym' => date('Ym',$now),
                    ];
                    array_push($turnover,$turnover_id_card_fee);
                    $turnover_pass_port_fee = [
                        'type' =>1,
                        'sub_type' =>1,
                        'subject' =>20,
                        'director_id' =>$info['director_id'],
                        'introducer_id' =>$info['is_introducer'] ==1?$info['introducer_id']:0,
                        'customer_id' => $data['id'],
                        'customer_idcard' =>$info['id_card'],
                        'amount' => $data['pass_port_fee'],
                        'related_index' => $data['id'],
                        'created_time' => $now,
                        'created_d' => date('Ymd',$now),
                        'created_y' => date('Y',$now),
                        'created_ym' => date('Ym',$now),
                    ];
                    array_push($turnover,$turnover_pass_port_fee);
                    $customer_log[] = [
                        'c_id' => $data['id'],
                        'id_card' => $info['id_card'],
                        'status' => $data['status'],
                        'create_by' => session('admin.userid'),
                        'create_time' => $now,
                    ];
                }

                Db::name("customer_log")->insertAll($customer_log);
                //流水表
                Db::name("turnover")->insertAll($turnover);
                Db::name("profit_loss_log")->insertAll($profit_loss_log);
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
            return json(['status'=>'00','msg'=>'修改成功']);
        }
    }

    //免护照认证费用转出
    function freePassport() {
        $idx =  $this->request->post('ids', '', 'strip_tags');
        if(!$idx) $this->error('参数错误');

        try {
            $where['id'] = explode(',',$idx);
            Db::startTrans();
            $data['pass_port_fee'] = $data['pass_port_certification_fee'] = $data['pass_port_lsg_fee'] = 0;
            $data['id_card_fee'] = 150;
            $data['id_card_certification_fee'] = 200;
            $data['id_card_lsg_fee'] = 1530;
            $data['status'] = 1;
            CustomerService::editWhere($where,$data);
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
        return json(['status'=>'00','msg'=>'修改成功']);

    }

	/*删除*/
	function delete(){
		$idx =  $this->request->post('ids', '', 'strip_tags');
		if(!$idx) $this->error('参数错误');
		try{
			$where['id'] = explode(',',$idx);
            CustomerService::delete($where);
		}catch(\Exception $e){
			$this->error($e->getMessage());
		}
		return json(['status'=>'00','msg'=>'操作成功']);
	}

	/*查看数据*/
	function view(){
		$id = $this->request->get('id','','intval');
		if(!$id) $this->error('参数错误');
		try{
			$this->view->assign('info',checkData(CustomerDb::getInfo($id)));
			return $this->display('record/customer/view');
		} catch (\Exception $e){
			$this->error($e->getMessage());
		}
	}

	/*导出*/
	function dumpData(){
		$where['username'] = $this->request->param('username', '', 'strip_tags,trim');
		$where['sex'] = $this->request->param('sex', '', 'strip_tags,trim');
		$where['mobile'] = $this->request->param('mobile', '', 'strip_tags,trim');
		$where['email'] = $this->request->param('email', '', 'strip_tags,trim');
		$where['headimg'] = $this->request->param('headimg', '', 'strip_tags,trim');
		$where['status'] = $this->request->param('status', '', 'strip_tags,trim');
		$where['province'] = $this->request->param('province', '', 'strip_tags');;
		$where['city'] = $this->request->param('city', '', 'strip_tags');;
		$where['district'] = $this->request->param('district', '', 'strip_tags');;

		$create_time_start = $this->request->param('create_time_start', '', 'strip_tags');
		$create_time_end = $this->request->param('create_time_end', '', 'strip_tags');
		$where['create_time'] = \xhadmin\CommonService::getTimeWhere($create_time_start,$create_time_end);

		$orderby = '';

		try {
			//此处读取前端传过来的 表格勾选的显示字段
			$fieldInfo = [];
			for($j=0; $j<100;$j++){
				$fieldInfo[] = $this->request->param($j);
			}
			$fieldInfo = \xhadmin\CommonService::filterEmptyArray($fieldInfo);
			$res = MemberService::dumpData(formatWhere($where),$orderby,array_unique($fieldInfo));
		} catch (\Exception $e) {
			$this->error($e->getMessage());
		}
	}

	/*导入*/
	function import(){
		if ($this->request->isPost()) {
			try{
				$key = 'Member';
				$result = \xhadmin\CommonService::importData($key);
				if (count($result) > 0) {
					Cache::set($key,$result,3600);
					return redirect('startImport');
				} else{
					$this->error('内容格式有误！');
				}
			}catch(\Exception $e){
				$this->error($e->getMessage());
			}
		}else {
			return $this->display('base/importData');
		}
	}

	//开始导入
	function startImport(){
		if(!$this->request->isPost()) {
			return $this->display('base/startImport');
		}else{
			$p = $this->request->post('p', '', 'intval');
			$data = Cache::get('Member');
			$export_per_num = config('my.export_per_num') ? config('my.export_per_num') : 50;
			$num = ceil((count($data)-1)/$export_per_num);
			if($data){
				$start = $p == 1 ? 2 : ($p-1) * $export_per_num + 1;
				if($data[$start]){
					$dt['percent'] = ceil(($p)/$num*100);
					try{
						for($i=1; $i<=$export_per_num; $i++ ){
						//根据中文名称来读取字段名称
							if($data[$i + ($p-1)*$export_per_num]){
								foreach($data[1] as $key=>$val){
									$fieldInfo = \app\admin\db\Field::getWhereInfo(['name'=>$val,'menu_id'=>526]);
									if($val && $fieldInfo){
									$d[$fieldInfo['field']] = $data[$i + ($p-1)*$export_per_num][$key];
									if($fieldInfo['type'] == 17){
										unset($d[$fieldInfo['field']]);
									}
									if(in_array($fieldInfo['type'],[7,12])){	//时间字段
										$d[$fieldInfo['field']] = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToTimestamp($data[$i + ($p-1)*$export_per_num][$key]);
									}
									if($fieldInfo['type'] == 5){	//密码字段
										$d[$fieldInfo['field']] = md5($data[$i + ($p-1)*$export_per_num][$key].config('my.password_secrect'));
									}
									if($fieldInfo['type'] == 17){	//三级联动字段
										$arrTitle = explode('|',$fieldInfo['field']);
										$arrValue = explode('-',$data[$i + ($p-1)*$export_per_num][$key]);
										if($arrTitle && $arrValue){
											foreach($arrTitle as $k=>$v){
												$d[$v] = $arrValue[$k];
											}
										}
									}
									if(in_array($fieldInfo['type'],[2,3,23])){	//下拉，单选，开关按钮
										$d[$fieldInfo['field']] = getFieldName($data[$i + ($p-1)*$export_per_num][$key],$fieldInfo['config']);
									}
									}
								}
								$d['create_time'] = time();
								if(($i + ($p-1)*$export_per_num) > 1){
                                    CustomerDb::createData($d);
								}
							}
						}
					}catch(\Exception $e){
						return json(['error'=>'01','msg'=>$e->getMessage()]);
					}
					return json(['error'=>'00','data'=>$dt]);
				}else{
					Cache::delete('Member');
					return json(['error'=>'10']);
				}
			}else{
				$this->error('当前没有数据');
			}
		}
	}

    function getThumbPic(){
        $detail = $this->request->post('detail','','strval');
        preg_match_all('/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/',$detail,$allImg);
        return json(['status'=>'00','imgurl'=>$allImg[1][0]]);
    }


    public function checkIdCard(){
    	$id_card=$this->request->param('id_card', '', 'strip_tags,trim');
        $ret = CustomerDb::countList(['id_card'=>$id_card]);
        if($ret) {
            return json(['status'=>'01','msg'=>'该客户已经存在']);
        }
       	return json(['status'=>'00','msg'=>'']);
    }




}

